package com.bnz.service.impl;

import com.bnz.dao.ClassesDao;
import com.bnz.dao.StudentDao;
import com.bnz.entity.Classes;
import com.bnz.entity.PageResult;
import com.bnz.entity.Student;
import com.bnz.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentImpl implements StudentService {

    // 引入StudentDao,ClassesDao
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private ClassesDao classesDao;

    // 1、查询所有数据
    @Override
    public List<Student> findAll() {
        // 1.1、查出所有数据
        List<Student> all = studentDao.findAll();
        // 1.2、对数据进行遍历，设置相关班级
        for (Student student : all) {
            // 1.3、根据获取的班级id（cid），找到对应的班级
            Optional<Classes> byCid = classesDao.findById(student.getCid());
            Classes classes = byCid.get();
            // 1.4、将班级名称与学生中的班级名称关联
            student.setCname(classes.getCname());
        }
        // 1.5、返回
        return all;
    }

    // 2、分页查询所有数据
    @Override
    public PageResult<Student> findByPage(int page, int pagesize) {
        // 2.1、开始分页查询
        Page<Student> studentPage = studentDao.findAll(PageRequest.of(page - 1, pagesize));
        for (Student student : studentPage.getContent()) {
            Optional<Classes> optional = classesDao.findById(student.getCid());
            Classes classes = optional.get();
            student.setCname(classes.getCname());
        }
        // 2.2、返回PageResult对象
        return new PageResult<Student>(studentPage.getTotalElements(), (long) studentPage.getTotalPages(),studentPage.getContent());
    }
}
